package cn.qyd.atomic;

import sun.misc.Unsafe;

import java.util.TreeSet;

/**
 * @author 邱运铎
 * @date 2024-03-24 23:14
 */
public class UnsafeVolatile {
    static class ThreadChange implements Runnable {
        /* volatile */ boolean flag = false;
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("subThread change flag to : " + flag);
            flag = true;
        }

        public boolean isFlag() {
            return flag;
        }
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Unsafe unsafe = UnsafeDemo01.getUnsafe();
        ThreadChange threadChange = new ThreadChange();
        Thread thread = new Thread(threadChange);
        thread.start();
        int count = 0;
        while (true) {
            boolean flag = threadChange.isFlag();
            //在使用flag前加上读屏障指令
            unsafe.loadFence();
            count++;
            if (flag) {
                System.out.println("detected flag changed ");
                break;
            }
        }
        //在未加上 unsafe.loadFence 读屏障 main线程无法感知子线程flag的改变，无法跳出循环
        System.out.println(count);
        System.out.println("main thread end ");
    }
}
